<?php
namespace app\common\model;

use think\Model;

class Log extends Model
{
    protected $pk = 'id';

    protected $auto = ['create_time', "admin_id"];

    protected function setCreateTimeAttr()
    {
        return time();
    }

    protected function setAdminIdAttr()
    {
        return session("admin")['id'];
    }

    public function getLogs($params, $page = 20, $order = "l.id desc")
    {
        $where = [];
        if (isset($params['pagezise'])) {
            $page = $params['pagezise'];
        }
        $field = "l.id,account,admin_id,content,l.create_time,name,datas";
        if (isset($params['keyword']) && $params['keyword'] != "") {
            $where['content'] = ['like', '%' . $params['keyword'] . '%'];
        }
        if (isset($params['start_date'])) {

            if ($params['start_date'] && $params['end_date']) {
                $start = strtotime($params['start_date']);
                $end   = strtotime($params['end_date']) + 86400;
                $list  = $this::alias('l')
                    ->field($field)
                    ->join("__ADMIN__ a", "l.admin_id = a.id")
                    ->whereTime('l.create_time', 'between', [$start, $end])
                    ->where($where)->order($order)->paginate($page);
            } else {
                $list = $this::alias('l')
                    ->field($field)
                    ->join("__ADMIN__ a", "l.admin_id = a.id")
                    ->where($where)->order($order)->paginate($page);
            }
        } else {
            $list = $this::alias('l')
                ->field($field)
                ->join("__ADMIN__ a", "l.admin_id = a.id")
                ->where($where)->order($order)->paginate($page);
        }

        $data = $list->toArray();
        return $data;
    }

    public function saveLog($data)
    {
        if ($this::save($data)) {
            return $this->id;
        }
    }

    public function delLog($where)
    {
        $this::where($where)->delete();
    }

}
